package part21;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wcj
 * @Date 2021/6/9 15:20
 * @Version 1.0
 */
public class Part2114 {

    public static void main(String[] args) {
        EvenChecker.test(new EvenGenerator());
    }
}

class EvenGenerator extends IntGenerator {
    private int currentVal = 0;

    @Override
    public int next() {
        ++currentVal;
        ++currentVal;
        return currentVal;
    }
}

abstract class IntGenerator {
    private volatile boolean cancel = false;

    public abstract int next();

    public void cancel() {
        cancel = true;
    }

    public boolean isCancel() {
        return cancel;
    }
}

class EvenChecker implements Runnable {
    private IntGenerator generator;
    private final int id;

    public EvenChecker(IntGenerator g, int id) {
        this.generator = g;
        this.id = id;
    }

    @Override
    public void run() {
        while (!generator.isCancel()) {
            int next = generator.next();
            if (next % 2 != 0) {
                System.out.println(next + " not even");
                generator.cancel();
            }
        }
    }

    public static void test(IntGenerator generator, int count) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < count; i++) {
            exec.execute(new EvenChecker(generator, i));
        }
        exec.shutdown();
    }

    public static void test(IntGenerator gp) {
        test(gp, 10);
    }
}
